<?php
/**
 * Save.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/06/12
 * Time: 09:51
 */
namespace app\api\open\member\address;

use app\api\open\member\Token;
use app\api\model\MemberAddressModel;
use think\Db;
use think\Validate;

class Save extends Token
{
    protected $id = null;
    protected $saveData = [];
    /**
     * Save constructor.
     * @throws \Exception
     */
    public function __construct($param=[])
    {
        parent::__construct($param);

        // 验证请求参数
        $validate = new Validate([
			"province" => "require",
			"city" => "require",
			"county" => "require",
			"tel" => "require",
			"alias" => "require",
			"name" => "require",
			"address" => "require",
			"is_default" => "require",
			"is_delete_time" => "require"
        ],[
			"province.require" => "所在省必填",
			"city.require" => "所在市必填",
			"county.require" => "所在县/区必填",
			"tel.require" => "电话必填",
			"alias.require" => "别名必填",
			"name.require" => "姓名必填",
			"address.require" => "详细地址必填",
			"is_default.require" => "是否默认地址（0否, 1是）必填",
			"is_delete_time.require" => "是否删除（0否，1删除时间戳）必填"
        ]);
        $check = $validate->check($this->params);
        if($check === false){
            // 验证失败 输出错误信息
            throw new \Exception($validate->getError(),1);
        }
        if(!empty($this->params['id']))
        {
            $this->id = $this->params['id'];
        }
        /**
         * 四个直辖市：北京市(id=1)、天津市(2)、上海市(9)、重庆市(22)
         */
		// 所在省
		$this->saveData['province'] = (int)$this->params['province'];
		// 所在市
		$this->saveData['city'] = (int)$this->params['city'];
		// 所在县/区
		$this->saveData['county'] = (int)$this->params['county'];
		// 会员ID
		$this->saveData['member_id'] = $this->member_id;
		// 经度
        if(!empty($this->params['lng']))
        {
            $this->saveData['lng'] = $this->params['lng'];
        }
		// 纬度
        if(!empty($this->params['lat']))
        {
            $this->saveData['lat'] = $this->params['lat'];
        }
		// 电话
		$this->saveData['tel'] = (string)$this->params['tel'];
		// 别名
		$this->saveData['alias'] = (string)$this->params['alias'];
		// 姓名
		$this->saveData['name'] = (string)$this->params['name'];
		// 详细地址
		$this->saveData['address'] = (string)$this->params['address'];
		// 是否默认地址（0否, 1是）
		$this->saveData['is_default'] = (int)$this->params['is_default'];
		// 是否删除（0否，1删除时间戳）
		$this->saveData['is_delete_time'] = (int)$this->params['is_delete_time'];
    }
    
    /**
     * @param array $param
     * @return array
     * @throws \Exception
     */
    public function index($param=[])
    {
        Db::startTrans();
        try
        {
            if($this->saveData['is_default'] == 1)
            {
                // 取消其他默认
                $status = MemberAddressModel::getInstance()->update(['member_id'=>$this->member_id],['is_default'=>0]);
                if(!$status)
                {
                    throw new \Exception("更新默认失败",2);
                }
            }
            // 保存信息
            $id = MemberAddressModel::getInstance()->save($this->id,$this->saveData);
            if(!$id)
            {
                throw new \Exception("保存失败",2);
            }
        }
        catch (\Exception $e)
        {
            // 出现错误进行回滚处理
            Db::rollback();
            // 统一错误抛出
            throw new \Exception("保存失败：".$e->getMessage(),$e->getCode());
        }

        Db::commit();
        return ['id'=>empty($this->id)?$id:$this->id];
    }
}